package com.example.myapplication;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;


public class MainActivity extends AppCompatActivity {

    private EditText etInput, tvOutput;
    private Button btnCopy, btnClear, btnExport;
    private SharedPreferences sharedPref;
    private Map<String, Integer> wordFrequencyMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        initViews();

        // 加载历史记录
        loadLastResult();

        // 设置监听器
        setupListeners();
    }

    private void initViews() {
        etInput = findViewById(R.id.et_input);
        tvOutput = findViewById(R.id.tv_output);
        btnCopy = findViewById(R.id.btn_copy);
        btnClear = findViewById(R.id.btn_clear);
        btnExport = findViewById(R.id.btn_export);
        sharedPref = getSharedPreferences("AppPrefs", MODE_PRIVATE);
    }

    private void setupListeners() {
        // 输入监听
        etInput.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                updateWordSegmentation(s.toString());
            }
        });

        // 按钮监听
        btnCopy.setOnClickListener(v -> copyToClipboard());
        btnClear.setOnClickListener(v -> clearAll());
        btnExport.setOnClickListener(v -> exportToFile());
    }

    // 核心分词逻辑
    private void updateWordSegmentation(String inputText) {
        String[] words = inputText.split("[^a-zA-Z;，、]+");
        wordFrequencyMap.clear();
        Set<String> uniqueWords = new LinkedHashSet<>(); // 保持插入顺序

        // 分词并统计词频
        for (String word : words) {
            if (!word.isEmpty()) {
                String lowerWord = word.toLowerCase();
                wordFrequencyMap.put(lowerWord, wordFrequencyMap.getOrDefault(lowerWord, 0) + 1);
                uniqueWords.add(word.toLowerCase());
            }
        }
        String result = String.join("\n", uniqueWords);
        tvOutput.setText(result);
        saveCurrentResult(inputText, result);
    }

    // 复制到剪贴板
    private void copyToClipboard() {
        String textToCopy = tvOutput.getText().toString();
        if (textToCopy.isEmpty()) {
            showToast(R.string.toast_empty);
            return;
        }

        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("分词结果", textToCopy));
        showToast(R.string.toast_copied);
    }

    // 清空内容
    private void clearAll() {
        etInput.setText("");
        tvOutput.setText("");
        wordFrequencyMap.clear();
        showToast(R.string.toast_cleared);
    }

    // 导出到文件
    private void exportToFile() {
        String content = tvOutput.getText().toString();
        if (content.isEmpty()) {
            showToast(R.string.toast_empty);
            return;
        }

        try (FileOutputStream fos = openFileOutput("word_segmentation.txt", Context.MODE_PRIVATE)) {
            fos.write(content.getBytes());
            showToast(R.string.toast_exported);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 保存当前结果到SharedPreferences
    private void saveCurrentResult(String input, String output) {
        sharedPref.edit()
                .putString("last_input", input)
                .putString("last_output", output)
                .apply();
    }

    // 加载记录
    private void loadLastResult() {
        String lastInput = sharedPref.getString("last_input", "");
        String lastOutput = sharedPref.getString("last_output", "");

        if (!lastInput.isEmpty()) {
            etInput.setText(lastInput);
            tvOutput.setText(lastOutput);
        }
    }

    // Toast工具方法
    private void showToast(int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }
}